<?php

namespace App\HttpController;

use App\HttpController\ApiBase;
use App\Models\UserModel;
use EasySwoole\Http\Message\Status;
use EasySwoole\Component\Di;
class UserBase extends ApiBase
{
    protected $who;
    // session 的 cookie 头
    protected $sessionKey = 'userSession';
    // 白名单
    protected $whiteList = ['login', 'register',"getloginuser"];

    /**
     * onRequest
     * @param null|string $action
     * @return bool|null
     * @throws \Throwable
     * @author yangzhenyu
     * Time: 13:49
     */
    function onRequest(?string $action): ?bool
    {
        var_dump("action is...".$action);
        if (parent::onRequest($action)) {
            // 白名单判断
            if (in_array($action, $this->whiteList)) {
                return true;
            }
            $user = $this->getWho();
            // 获取登入信息
           
       
            if (!$user) {
                $this->writeJson(Status::CODE_UNAUTHORIZED, '', '登入已过期');
                return false;
            }
            // 刷新 cookie 存活
            $this->response()->setCookie($this->sessionKey, $this->getWho()['userSession'], time() + 3600, '/');

            return true;
        }
        return false;
    }

    /**
     * getWho
     * @author yangzhenyu
     * Time: 13:51
     */
    function getWho()
    {
        if ($this->who) {
            return $this->who;
        }
      
        $sessionKey = $this->request()->getCookieParams($this->sessionKey);
        var_dump($sessionKey);
        if (empty($sessionKey)) {
            return null;
        }
        $redis=\EasySwoole\Pool\Manager::getInstance()->get('redis')->getObj();

        $userInfo =$redis->get(sprintf("logintoken-%s",$sessionKey));
        
        \EasySwoole\Pool\Manager::getInstance()->get('redis')->recycleObj($redis);
      
        if ($userInfo) {
        	$userInfo = json_decode($userInfo,true);
        }else{
        	return null;
        }
        $userInfo['userSession'] = $sessionKey;

        $this->who = $userInfo;
        return $this->who;
    }
}